import store from '@/store'
import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { showConfirm, tansParams, toast } from '@/utils/common'

let timeout = 10000
const baseUrl = config.baseUrl

const request = config => {
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    config.headers = config.headers || {}
    if (getToken() && !isToken) {
        // config.headers['Authorization'] = 'Bearer ' + getToken()
        config.headers['Authorization'] = getToken()
    }
    // get请求映射params参数
    if (config.params) {
        let url = config.url + '?' + tansParams(config.params)
        url = url.slice(0, -1)
        config.url = url
    }
    return new Promise((resolve, reject) => {
        uni.request({
            method: config.method || 'get',
            timeout: config.timeout || timeout,
            url: config.baseUrl || baseUrl + config.url,
            data: config.data,
            header: config.headers,
            dataType: 'json',
            success(result) {
                const res = result.data
                if (res.status) {
                    resolve(res.data);
                } else {
                    const msg = res.message
                    reject(msg);
                }
            },
            fail(err) {
                // 隐藏加载中
                console.log('可能超时了')
                reject(err);
            }
        })
    });
}

export default request
